﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyBlog.Common;
using MyBlog.Model;
using Webdiyer.WebControls.Mvc;

namespace MyBlog.Web.Controllers
{
    public class MessageController : BaseController
    {
        [TrackRequest]
        public ActionResult Index()
        {
            var all = XiaoBoKe.MessageService.GetAll(new MessageModel { AccountId = this.CurBlogUserID }, false);
            ViewBag.TotalPage = all.Count() % 15 == 0 ? (all.Count / 15) : (all.Count / 15 + 1);
            ViewBag.total = all.Count;
            ViewBag.BlogUserName = CurBlogUserName;
            return View();
        }

        public PartialViewResult _UserMessagePage(string username, int page = 1)
        {
            var mess = XiaoBoKe.MessageService.GetAll(new MessageModel { AccountId = username }, false)
               .OrderByDescending(x => x.MsgTime).ToPagedList(page, 15);
            ViewBag.CanEdit = CanEdit;
            return PartialView(mess);
        }

        [Authenticate(false)]
        [HttpPost]
        public JsonResult SendMessage(MessageModel model)
        {
            model.VisitorIP = UserSession.GetClientIP();
            model.MsgTime = DateTime.Now;
            model.AccountId = this.CurBlogUserID;
            model.VisitUid = UserSession.AccountId;
            XiaoBoKe.MessageService.Add(model);
            try
            {
                if (!CurBlogUserID.Same(UserSession.AccountId))
                {
                    var notice = WebCache.GetNickName(UserSession.AccountId) + "给你留言：" + model.Content.StripHTML();
                    EmailHelper.SendMail(WebCache.GetAccount(CurBlogUserID).Email, "小博客留言通知", notice);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("发送留言通知出错：" + ex.Message);
            }
            return Json(new JsonData { State = AjaxState.Success });
        }

        [HttpPost]
        [Authenticate]
        public JsonResult SaveUserWantSay(string wantsay)
        {
            XiaoBoKe.AccountService.SaveUserWantSay(UserSession.AccountId, wantsay);
            return Json(new JsonData { State = AjaxState.Success });
        }

        public string GetUserWantSay()
        {
            string word = XiaoBoKe.AccountService.Get(CurBlogUserID).WantSay;
            return !string.IsNullOrWhiteSpace(word) ? word : "<span>欢迎光临我的博客^_^</span>";
        }

        [HttpPost]
        [Authenticate(false)]
        public JsonResult DelMsg(int id)
        {
            var msg = XiaoBoKe.MessageService.Get(id);
            if (msg.MsgReplyModels.Count > 0)
            {
                foreach (var item in msg.MsgReplyModels)
                {
                    XiaoBoKe.MsgReplyService.Delete(item.ID);
                }
            }
            XiaoBoKe.MessageService.Delete(id);
            return Json(new JsonData { State = AjaxState.Success });
        }

        [HttpPost]
        [Authenticate(false)]
        public JsonResult DelRpMsg(int id)
        {
            XiaoBoKe.MsgReplyService.Delete(id);
            return Json(new JsonData { State = AjaxState.Success });
        }

        [HttpPost]
        [Authenticate(false)]
        public JsonResult ReplyMsg(int id, string content)
        {
            var rep = new MsgReplyModel { MsgId = id, Content = content, ReplyTime = DateTime.Now, ReplyUid = UserSession.AccountId };
            XiaoBoKe.MsgReplyService.Add(rep);
            var msg = WebCache.GetAccount(CurBlogUserID).MessageModels.First(x => x.ID == id);
            base.AddNotice(UserSession.AccountId, NoticeEnum.ReplyMsg, ExtensionMethod.BuildLink(Url.Action("index"), msg.Content.HtmlDecode()), content);
            try
            {
                var item = XiaoBoKe.MessageService.Get(id);
                if (!item.AccountId.Same(UserSession.AccountId))
                {
                    var notice = WebCache.GetNickName(UserSession.AccountId) + "回复：" + content.StripHTML();
                    EmailHelper.SendMail(WebCache.GetAccount(item.AccountId).Email, "小博客留言回复通知", notice);
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteLog("发送留言回复通知出错：" + ex.Message);
            }
            return Json(new JsonData { State = AjaxState.Success });
        }

        [HttpPost]
        public JsonResult Agree(int id)
        {
            var model = XiaoBoKe.MessageService.Get(id);
            if (string.IsNullOrWhiteSpace(model.AgreeUsers) || (!string.IsNullOrWhiteSpace(model.AgreeUsers) && !model.AgreeUsers.Contains(UserSession.AccountId)))
            {
                XiaoBoKe.MessageService.AddAgree(id, UserSession.AccountId);
                return Json(new JsonData { State = AjaxState.Success });
            }
            else
            {
                return Json(new JsonData { State = AjaxState.Fail, Message = "你已经点过赞啦！" });
            }
        }

        [HttpPost]
        public JsonResult AgreeReply(int id)
        {
            var model = XiaoBoKe.MsgReplyService.Get(id);
            if (string.IsNullOrWhiteSpace(model.AgreeUsers) || (!string.IsNullOrWhiteSpace(model.AgreeUsers) && !model.AgreeUsers.Contains(UserSession.AccountId)))
            {
                XiaoBoKe.MsgReplyService.AddAgree(id, UserSession.AccountId);
                return Json(new JsonData { State = AjaxState.Success });
            }
            else
            {
                return Json(new JsonData { State = AjaxState.Fail, Message = "你已经点过赞啦！" });
            }
        }

    }
}
